local mt = { }

---private
function mt.decode(message)
    local f, err = load('return '.. message)
    if not f then
        print(err)
        print(debug.traceback())
        return nil
    end
    local suc, res = pcall(f)
    if not suc then
        print(res)
        print(debug.traceback())
        return nil
    end
    return res
end

---private
function mt.encode(tbl)
    local type = type
    local pairs = pairs
    local format = string.format
    local find = string.find
    local tostring = tostring
    local tonumber = tonumber
    local mark = {}
    local buf = {}
    local count = 0
    local function dump(v)
        local tp = type(v)
        if mark[v] then
            error('表结构中有循环引用')
        end
        mark[v] = true
        buf[#buf+1] = '{'
        local ator = pairs
        if #v > 0 then
            ator = ipairs
        end
        for k, v in ator(v) do
            count = count + 1
            if count > 1000 then
                error('表太大了')
            end
            local tp = type(k)
            if tp == 'number' then
                if ator == pairs then
                    buf[#buf+1] = format('[%s]=', k)
                end
            elseif tp == 'string' then
                if find(k, '[^%w_]') then
                    buf[#buf+1] = format('[%q]=', k)
                else
                    buf[#buf+1] = k..'='
                end
            else
                error('不支持的键类型：'..tp)
            end
            local tp = type(v)
            if tp == 'table' then
                dump(v)
            elseif tp == 'number' then
                buf[#buf+1] = format('%q', v)
            elseif tp == 'string' then
                buf[#buf+1] = format('%q', v)
            elseif tp == 'boolean' then
                buf[#buf+1] = format('%s', v)
            else
                log.error('不支持的值类型：'..tp)
            end
            buf[#buf+1] = ','
        end
        if buf[#buf] == ',' then
            table.remove(buf, #buf)
        end
        buf[#buf+1] = '}'
    end
    dump(tbl)
    return table.concat(buf)
end

return mt 